package org.grenobus.html;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Map;

import android.util.Log;

public class Form {

	private String fAction;
	private ArrayList<Field> fFields = new ArrayList<Field>(); 
	private FieldSelect fLastSelect;
	
	private final String ENCODING = "iso-8859-1";

	public Form(String action) {
		fAction = action;
	}
	
	public void addField(Field field) {
		fFields.add(field);
		if (field instanceof FieldSelect)
			fLastSelect = (FieldSelect)field;
	}
	
	public String getAction() {
		return fAction;
	}
	
	public ArrayList<Field> getFields() {
		return fFields;
	}
	
	public void addOption(String val, String display) {
		if (fLastSelect != null)
			fLastSelect.addChoice(val, display);
	}
	
	public String buildActionURL(String baseURL, Map<String,String> properties, String selectName, int selectPos) {
		String url = baseURL + getAction() + "?";
		boolean first = true;

		try {
			for (Field f : getFields()) {
				if (!first)
					url += "&";

				first = false;
				
				if (f.getName().equals(selectName) && f instanceof FieldSelect) {
					FieldSelect select = (FieldSelect)f;
					String val = select.fChoices.get(selectPos).value;
					properties.put(f.getName(), val);
				}
				
				String prop = properties.get(f.getName()); 
				if (prop != null) {
					url += URLEncoder.encode(f.getName(), ENCODING);
					url += "=" + URLEncoder.encode(prop, ENCODING);
				} else if (f instanceof FieldInput) {
					FieldInput input = (FieldInput)f;
					url += URLEncoder.encode(input.getName(), ENCODING);
					url += "=" + URLEncoder.encode(input.getValue(), ENCODING);
				} else {
					Log.w("TextView", "Unhandled field: " + f.getName());
				}
			}
		} catch (UnsupportedEncodingException e) {
			return null;
		}
		
		System.out.println(url);
		return url;
	}
}
